#  This file is part of OpenLightingDesigner.
# 
#  OpenLightingDesigner is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  OpenLightingDesigner is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with OpenLightingDesigner.  If not, see <http://www.gnu.org/licenses/>.
#
# basemacro.py
# Copyright (c) 2010 - 2011 Matthew Reid

from Bases import OSCBaseObject, setID

class BaseMacro(OSCBaseObject):
    _Properties = {'name':dict(default=''), 
                   'duration':dict(default=1.), 
                   'running':dict(default=False, quiet=True)}
    def __init__(self, **kwargs):
        super(BaseMacro, self).__init__(**kwargs)
        self.MainController = kwargs.get('MainController')
        if 'deserialize' not in kwargs:
            self.id = setID(kwargs.get('id'))
            self.name = kwargs.get('name', self.__class__.__name__)
            self.duration = kwargs.get('duration', 1.)
        self.controllers = set()
        self.init_macro(**kwargs)
    def init_macro(self, **kwargs):
        pass
    def add_controller(self, c):
        if self.running:
            return False
        self.sequencer.add_controller(c)
        self.controllers.add(c)
    def remove_controllers(self):
        for c in self.controllers:
            self.sequencer.del_controller(c)
            c.unlink()
        self.controllers.clear()
    def run(self):
        if self.running:
            return False
        if not self._check_run():
            return False
        self.sequencer = self.MainController.EffectsSystem.add_sequencer(duration=self.duration)
        self.sequencer.bind(state_changed=self.on_sequencer_state)
        self._prepare_run()
        self.sequencer.start()
        self.running = True
        return True
    def on_sequencer_state(self, **kwargs):
        state = kwargs.get('state')
        if not state:
            self._prepare_stop()
            self.remove_controllers()
            self.running = False
            self.MainController.EffectsSystem.del_sequencer(sequencer=self.sequencer)
            self.sequencer = None
    def _check_run(self):
        return True
    def _prepare_run(self):
        pass
    def _prepare_stop(self):
        pass
        
